/*global define $win*/
define(['jquery'], function($) {
    function SelectDateTime(param) {
        this.params = $.extend({
            wrap: null, //div
            isMonthDefault: true, //是否展示默认月份，从当前月开始展示后面一年。默认为true
            isHasTime: false, //点击时是否有时间显示，默认为false
            monthArray: null, //isMonthDefault为true时，当前参数失效
            isMultiSelect: true, //true:可以选择连续多个日期, false:只选择单个日期
            initDateTime: null, //默认加载日期，只在展示月份中展示日期；单选时只能有一个日期，多选时只能有两个区间日期
            YcallBack: null,
            NcallBack: null
        }, param);

        this.$date_wrapper;
        this.$content;
        this.$scroll;
        this.$scrollWapper;
        this.$timeWrapper;
        this.showYear;
        this.showMonth;
        this.$html;
        this.waiting = $("<div id=\"dateWaiting\" class=\"bg_popup\"></div>");
        this.waiting.append("<div class='loader-waiting'></div>");
        this._multiCount = 0;
        this.currentDateTime;
        this.initUIHeader();
    }

    SelectDateTime.prototype.initUIHeader = function() {
        var _this = this;
        if (!_this.params.wrap) {
            console.error("wrap参数未指定");
            return;
        }
        _this.$date_wrapper = $("#" + _this.params.wrap);
        _this.$scrollWapper = $("<div id='wrapper' class='wrapper' style='position:absolute;top:40px;'></div>");

        _this.$scroll = $("<div class='scroller' id='scroller'></div>");

        var str = "<div class='container-fluid datetime_header' style='height:40px;padding:0px;'>";
        str += "       <table class='table date_header_table'>";
        str += "           <tr class='iswhite'>";
        str += "              <td class='date_header_td'>一</td>";
        str += "              <td class='date_header_td'>二</td>";
        str += "              <td class='date_header_td'>三</td>";
        str += "              <td class='date_header_td'>四</td>";
        str += "              <td class='date_header_td'>五</td>";
        str += "              <td class='isred date_header_td'>六</td>";
        str += "              <td class='isred date_header_td'>日</td>";
        str += "           </tr>";
        str += "       </table>";
        str += "   </div>";
        _this.$date_wrapper.append(str);
        _this.$scrollWapper.append(_this.$scroll);
        _this.$date_wrapper.append(_this.$scrollWapper);

        $("#wrapper").height(_this.$date_wrapper.height() - $(".datetime_header").height());
        if (_this.params.isHasTime) {
            _this.buildTime();
        }
        _this.initData();
    };

    /**
     * [根据配置是否加载默认日期加载日期数据]
     */
    SelectDateTime.prototype.initData = function() {
        var _this = this;
        if (_this.params.isMonthDefault) {
            _this.initBodyData(_this.defaultMonth());
        } else {
            var aMonthArray = _this.params.monthArray;
            if ($.isArray(aMonthArray)) {
                if (aMonthArray.length == 1) {
                    var yearmonth = aMonthArray[0].split("-");
                    _this.initBody(yearmonth[0], yearmonth[1]);
                } else if (aMonthArray.length == 2) {
                    var monthObj = _this.getYearAndMonth(aMonthArray[0], aMonthArray[1]);
                    _this.initBodyData(monthObj);
                }
            } else {
                console.error("月份不是数组格式.");
            }
        }
        _this.initEvent();
    };

    /**
     * [加载日期数据]
     * @param  {[array]} yearmonthArray [日期数组]
     */
    SelectDateTime.prototype.initBodyData = function(yearmonthArray) {
        var _this = this;
        for (var i = 0; i < yearmonthArray.length; i++) {
            var yearmonth = yearmonthArray[i].split("-");
            _this.initBody(yearmonth[0], yearmonth[1]);
        }
    };

    SelectDateTime.prototype.selectDate = function() {
        var _this = this;
        if (_this.params.isMultiSelect) {
            if ($.isArray(_this.params.initDateTime)) {
                var selectdateArray = _this.params.initDateTime;
                if (selectdateArray.length == 2) {
                    _this._multiCount == 2;
                    var start = selectdateArray[0];
                    var end = selectdateArray[1];
                    _this.addMultiSelected(start, end);
                } else {
                    console.error("加载选择日期失败,多选日期中应只包含起止日期。");
                }
            }
            //选择连续多个日期
            $(".date_body_td").unbind("click").bind("click", function() {
                if ($(this).text().trim() == "") {
                    return;
                }
                if ($(this).hasClass("backgroundstyle") && _this._multiCount == 1) {
                    $(this).removeClass("backgroundstyle");
                    $(".time_show").remove();
                    _this._multiCount = 0;
                    return;
                }
                if (_this._multiCount >= 2) {
                    $(".backgroundstyle").removeClass("backgroundstyle");
                    $(".time_show").remove();
                    _this._multiCount = 0;
                }
                $(this).addClass("backgroundstyle");
                _this._multiCount++;
                if (_this.params.isHasTime) {
                    _this.currentDateTime = $(this);
                    var _currentDateTime = $(this);
                    _this.showTime(_currentDateTime);
                }
                if (_this._multiCount == 2) {
                    var start = $($(".backgroundstyle")[0]).attr("ddate");
                    var end = $($(".backgroundstyle")[1]).attr("ddate");
                    _this.addMultiSelected(start, end);
                }

            });
        } else {
            if ($.isArray(_this.params.initDateTime)) {
                var ddate = _this.params.initDateTime;
                var ddateArray = ddate[0].split("-");
                var selectYear = ddateArray[0];
                var selectMonth = parseInt(ddateArray[1]) < 10 ? "0" + parseInt(ddateArray[1]) : ddateArray[1];
                var selectDay = ddateArray[2];
                var selectdate = selectYear + "-" + selectMonth + "-" + selectDay;
                $("[ddate = " + selectdate + "]").addClass("backgroundstyle");
                console.log("单选：" + selectdate);
            }
            //选择单个日期
            $(".date_body_td").unbind("click").bind("click", function() {
                if ($(this).text().trim() == "") {
                    return;
                }
                if ($(this).hasClass("backgroundstyle")) {
                    $(this).removeClass("backgroundstyle");
                } else {
                    $(".backgroundstyle").removeClass("backgroundstyle");
                    $(this).addClass("backgroundstyle");
                    console.log("单选：" + $(this).attr("ddate"));
                }
            });
        }
    };

    /**
     * [buldTimeUI 展示时间]
     * @return {[type]} [description]
     */
    SelectDateTime.prototype.showTime = function(_currentDateTime) {
        var _this = this;
        _this.waiting.show();
        _this.$timeWrapper.show();
        var min_div = $win.touchScroll5("#min_div");
        var second_div = $win.touchScroll5("#second_div");
        var tempminValue = 0;
        min_div.on("scrollEnd", function() {
            var scroll_y = Math.abs(this.y);
            if (tempminValue == scroll_y) {
                return false;
            }
            var scroll_height = Math.abs(this.scrollerHeight);
            var lichild = Math.round(scroll_y / (scroll_height / 26));
            tempminValue = scroll_y;
            lichild = '#min_div ul li:nth-child(' + (parseInt(lichild) + 2) + ')';
            $(".addMinClass").removeClass("addMinClass");
            $(lichild).addClass("addMinClass");
            this.scrollToElement(lichild, 200, null, true);
        });
        var tempSecValue = 0;
        second_div.on("scrollEnd", function() {
            var scroll_y = Math.abs(this.y);
            if (tempSecValue == scroll_y) {
                return false;
            }
            var scroll_height = Math.abs(this.scrollerHeight);
            var lichild = Math.round(scroll_y / (scroll_height / 8));
            tempSecValue = scroll_y;
            lichild = '#second_div ul li:nth-child(' + (parseInt(lichild) + 2) + ')';
            $(".addSecondClass").removeClass("addSecondClass");
            $(lichild).addClass("addSecondClass");
            this.scrollToElement(lichild, 200, null, true);
        });

        _this.bindTimeEvent(_currentDateTime);
    };

    /**
     * 展示时间
     * @return {[type]} [description]
     */
    SelectDateTime.prototype.buildTime = function() {
        var _this = this;
        var datetime_footer = $("<div class='datetime_footer'></div>");
        datetime_footer.append("<div class='col-xs-2 time_div'></div>");
        var dateMinDiv = $("<div class='col-xs-2 time_div' id='min_div'></div>");
        var dateMinUl = $("<ul class='time_ul scroller'></ul>");
        var dateMinLi = "<li>&nbsp;</li>";
        for (var i = 0; i < 24; i++) {
            dateMinLi += "<li>" + i + "</li>";
        }
        dateMinLi += "<li>&nbsp;</li>";
        dateMinUl.append(dateMinLi);
        dateMinDiv.append(dateMinUl);
        dateMinDiv.append("<hr class='col-xs-12 hr_style' style='top:50px;'></hr>");
        dateMinDiv.append("<hr class='col-xs-12 hr_style' style='top:90px;'></hr>");
        datetime_footer.append(dateMinDiv);
        datetime_footer.append("<div class='col-xs-1 time_div'></div>");

        var dateSecondDiv = $("<div class='col-xs-2 time_div' id='second_div'></div>");
        var dateSecondUl = $("<ul class='time_ul scroller'></ul>");
        var dateSecondLi = "<li>&nbsp;</li>";
        for (var k = 0; k <= 50; k += 10) {
            dateSecondLi += "<li>" + ((k < 10) ? ("0" + k) : k) + "</li>";
        }
        dateSecondLi += "<li>&nbsp;</li>";
        dateSecondUl.append(dateSecondLi);
        dateSecondDiv.append(dateSecondUl);
        dateSecondDiv.append("<hr class='col-xs-12 hr_style' style='top:50px;'></hr>");
        dateSecondDiv.append("<hr class='col-xs-12 hr_style' style='top:90px;'></hr>");
        datetime_footer.append(dateSecondDiv);

        datetime_footer.append("   <button id='closeTime' class='btn btn-primary btn_time'>确定 </button> ");
        _this.$timeWrapper = datetime_footer;
        _this.$date_wrapper.append(_this.waiting).append(_this.$timeWrapper);
        _this.hideTime();

    };

    /**
     * 隐藏时间
     * @return {[type]} [description]
     */
    SelectDateTime.prototype.hideTime = function() {
        var _this = this;
        _this.waiting.hide();
        _this.$timeWrapper.hide();
        $("#closeTime").unbind("click");
    };

    /**
     * [bindTimeEvent 绑定时间中的方法]
     * @return {[type]} [description]
     */
    SelectDateTime.prototype.bindTimeEvent = function(_currentDateTime) {
        var _this = this;
        $("#closeTime").unbind("click").bind("click", function() {
            var minValue = $(".addMinClass").text().trim();
            var secondValue = $(".addSecondClass").text().trim();
            _this.hideTime();
            console.log(minValue + ":" + secondValue);
            _currentDateTime.append("<div class='time_show'>" + minValue + ":" + secondValue + "</div>");
        });
    };

    /**
     * [获取多选的日期]
     */
    SelectDateTime.prototype.addMultiSelected = function(start, end) {
        var _this = this;
        var startTime = _this.getDate(start);
        var endTime = _this.getDate(end);
        while ((endTime.getTime() - startTime.getTime()) >= 0) {
            var year = startTime.getFullYear();
            var month = (startTime.getMonth() + 1).toString().length == 1 ? "0" + (startTime.getMonth() + 1).toString() : (startTime.getMonth() + 1);
            var day = (startTime.getDate()).toString().length == 1 ? "0" + (startTime.getDate()).toString() : (startTime.getDate());
            console.log(year + "-" + month + "-" + day);
            var addClassTD = year + "-" + month + "-" + day;
            $("[ddate='" + addClassTD + "']").addClass("backgroundstyle");
            _this._multiCount++;
            startTime.setDate(startTime.getDate() + 1);
        }
    };

    SelectDateTime.prototype.getDate = function(datestr) {
        var temp = datestr.split("-");
        var date = new Date(temp[0], temp[1] - 1, temp[2]);
        return date;
    };

    /**
     * [默认展示当前月往后一年的月份]
     * @return {[Array]}  result  [返回日期数组]
     */
    SelectDateTime.prototype.defaultMonth = function() {
        var dd = new Date();
        var dm = dd.getMonth() + 1;
        var now = dd.getFullYear() + "-" + (dm < 10 ? "0" + dm : dm);
        var d = new Date(now.replace(/[^\d]/g, "/") + "/1");
        var result = [now];
        for (var i = 0; i < 11; i++) {
            d.setMonth(d.getMonth() + 1);
            var m = d.getMonth() + 1;
            m = m < 10 ? "0" + m : m;
            result.push(d.getFullYear() + "-" + m);
        }
        return result;
    };

    /**
     * [获取两个月份之间的所有月份]
     * @param  {[string]} start [开始月份]
     * @param  {[string]} end   [结束月份]
     * @return {[Array]}  result [返回日期对象数组]
     */
    SelectDateTime.prototype.getYearAndMonth = function(start, end) {
        var result = [];
        var starts = start.split('-');
        var ends = end.split('-');
        var staYear = parseInt(starts[0]);
        var staMon = parseInt(starts[1]);
        var endYear = parseInt(ends[0]);
        var endMon = parseInt(ends[1]);
        var aStaMon = staMon < 10 ? "0" + staMon : staMon;
        result.push(staYear + "-" + aStaMon);
        while (staYear <= endYear) {
            if (staYear === endYear) {
                while (staMon < endMon) {
                    staMon++;
                    staMon = staMon < 10 ? "0" + staMon : staMon;
                    result.push(staYear + "-" + staMon);
                }
                staYear++;
            } else {
                staMon++;
                if (staMon > 12) {
                    staMon = 1;
                    staYear++;
                }
                staMon = staMon < 10 ? "0" + staMon : staMon;
                result.push(staYear + "-" + staMon);
            }
        }
        return result;
    };

    SelectDateTime.prototype.initEvent = function() {
        $win.touchScroll5("#wrapper");
        this.selectDate();
    };

    SelectDateTime.prototype.initBody = function(year, month) {
        var _this = this;
        _this.$content = $("<div class='date_month'></div>");

        //绑定日历表头
        var selectDateName = year + "年" + month + "月";
        var pEle = "<p class='date_month_name'>" + selectDateName + "</p>";
        _this.$content.append(pEle);
        //绑定日历
        var dateHtml = _this.drawCal(year, month);
        _this.$content.append(dateHtml);
        _this.$scroll.append(_this.$content);
    };

    SelectDateTime.prototype.buildCal = function(year, month) {
        var _this = this;
        var aMonth = new Array();
        aMonth[1] = new Array(7);
        aMonth[2] = new Array(7);
        aMonth[3] = new Array(7);
        aMonth[4] = new Array(7);
        aMonth[5] = new Array(7);
        aMonth[6] = new Array(7);
        aMonth[7] = new Array(7);
        var dCalDate = new Date(year, month - 1, 1);
        var iDayOfFirst = dCalDate.getDay();
        if (iDayOfFirst == 0) {
            iDayOfFirst = 7;
        }
        var iDaysInMonth = _this.getDaysInmonth(year, month);
        var iVarDate = 1;
        var d, w;
        for (d = iDayOfFirst; d < 8; d++) {
            aMonth[1][d] = iVarDate;
            iVarDate++;
        }
        for (w = 2; w < 8; w++) {
            for (d = 1; d < 8; d++) {
                if (iVarDate <= iDaysInMonth) {
                    aMonth[w][d] = iVarDate;
                    iVarDate++;
                }
            }
        }
        return aMonth;
    };

    SelectDateTime.prototype.getDaysInmonth = function(year, month) {
        var dPrevDate = new Date(year, month, 0);
        return dPrevDate.getDate();
    };

    SelectDateTime.prototype.drawCal = function(year, month) {
        var _this = this;
        var myMonth = _this.buildCal(year, month);
        var htmlArray = new Array();
        htmlArray.push("<div class='datetime'>");
        htmlArray.push("<table class='table date_body_table'>");
        var d, w;
        var tr_nums = _this.getBuildRow(year, month);
        for (w = 1; w < tr_nums + 1; w++) {
            htmlArray.push("<tr>");
            for (d = 1; d < 8; d++) {
                var monthday = !isNaN(myMonth[w][d]) ? myMonth[w][d] : "";
                var aDay = parseInt(monthday) < 10 ? "0" + parseInt(monthday) : monthday;
                if (d == 6 || d == 7) {
                    htmlArray.push("<td ddate='" + year + "-" + month + "-" + aDay + "' class='isred date_body_td'>" + monthday + "</td>");
                } else {
                    htmlArray.push("<td ddate='" + year + "-" + month + "-" + aDay + "' class='date_body_td'>" + monthday + "</td>");
                }

            }
            htmlArray.push("</tr>");
        }
        htmlArray.push("</table>");
        htmlArray.push("</div>");
        return htmlArray.join('');
    };

    SelectDateTime.prototype.getBuildRow = function(year, month) {
        var dCalDate = new Date(year, month - 1, 1);
        var iDayOfFirst = dCalDate.getDay();
        if (iDayOfFirst == 0) {
            iDayOfFirst = 7;
        }
        var dDate = new Date(year, month, 0);
        var daycount = dDate.getDate();
        var tr_nums = Math.ceil((iDayOfFirst + daycount) / 7);
        return tr_nums;
    };
    return SelectDateTime;
});
